package com.szmirren.vxApi.core.common.mq;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @ClassName : RocketMQProducer
 * @Description :
 * @Author : 孙亮
 * @Date: 2020-11-19 16:16
 */
public class RocketMQProducer {

    private static final Logger LOG = LogManager.getLogger(RocketMQProducer.class);

    public static void main(String[] args) throws MQClientException {
//        DefaultMQProducer producer = new DefaultMQProducer(RocketMQConfig.producerGroup);
//        producer.setNamesrvAddr(RocketMQConfig.host);
//        producer.setInstanceName(RocketMQConfig.producerInstanceName);
//        producer.start();
//        try {
//            for (int i = 0; i < 10; i++) {
//                Thread.sleep(1000); //每秒发送一次
//                Message msg = new Message(RocketMQConfig.Topic, // topic 主题名称
//                        RocketMQConfig.tag, // tag 临时值
//                        ("sunliang-" + i).getBytes()// body 内容
//                );
//                SendResult sendResult = producer.send(msg);
//                System.out.println(sendResult.toString());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        producer.shutdown();
        sendMsg("test.....");
    }

    private static final DefaultMQProducer producer = new DefaultMQProducer(RocketMQConfig.producerGroup);

    static {
        producer.setNamesrvAddr(RocketMQConfig.host);
        producer.setInstanceName(RocketMQConfig.producerInstanceName);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public static void sendMsg(String message) {
        Message msg = new Message(RocketMQConfig.Topic, // topic 主题名称
                RocketMQConfig.tag, // tag 临时值
                message.getBytes()// body 内容
        );
        try {
            SendResult sendResult = producer.send(msg);
            LOG.info(sendResult.toString());
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        producer.shutdown();
    }

}
